package com.woniu.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import me.chanjar.weixin.common.util.crypto.WxCryptUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序工具类，提供解密手机号等功能
 */
public class WechatUtil {

    // JSON解析器
    private  final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 解密微信小程序手机号
     *
     * @param encryptedData 加密的手机号数据
     * @param sessionKey 会话密钥
     * @param iv 加密算法的初始向量
     * @return 解密后的手机号信息，失败时返回null
     */
    public  Map<String, Object> decryptPhoneNumber(String encryptedData, String sessionKey, String iv) {
        try {
            // 解码Base64字符串
            byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            // 验证sessionKey长度
            if (sessionKeyBytes.length != 24) {
                throw new IllegalArgumentException("sessionKey长度必须为24字节");
            }

            // 初始化AES解密
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // 执行解密
            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

            // 转换为字符串
            String decryptedData = new String(decryptedBytes, StandardCharsets.UTF_8);

            // 解析JSON数据
            return objectMapper.readValue(decryptedData, HashMap.class);
        } catch (Exception e) {
            System.err.println("解密手机号失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    public String getPhoneNumber(String encryptedData, String sessionKey, String iv) {
        Map<String, Object> phoneInfo = decryptPhoneNumber(encryptedData, sessionKey, iv);
        if (phoneInfo != null) {
            return (String) phoneInfo.get("phoneNumber");
        }
        return null;
    }
}
